/**
 * @author Eddie
 * @date 2023-10-24
 * 营养膳食相关接口(对外提供，例如大屏)
 */

const router = require('koa-router')();
const fs = require('fs');

// 定义路由前缀，没有可不添加
router.prefix('/api/food');

// 获取营养膳食
router.get('/getYysh', async (ctx, next) => {
  try {
    let yyshObj = fs.readFileSync('./files/yysh.json', 'utf8');
    // 因为不同的域名都可以访问，所以返回当前域名的 host
    let returnObj = JSON.parse(yyshObj);
    returnObj["host"] = "http://" + ctx.host + "/images";
    ctx.body = {
      code: 1,
      msg: "读取成功",
      data: returnObj
    }
  } catch (error) {
    console.log("getYysh：", error);
    ctx.body = {
      code: -1,
      msg: "读取失败：" + error,
      data: {}
    }
  }
})

// 添加营养膳食
router.post('/addYysh', async (ctx, next) => {
  let data = ctx.request.body;
  let re = {};
  const week = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];
  for (const item of week) {
    if (data[item]) {
      for (const it in data[item]) {
        if (data[item][it]["url"] && data[item][it]["url"] != "") {
          data[item][it]["url"] = data[item][it]["url"].split("images")[1];
        }
      }

    }
  }

  try {
    fs.writeFileSync('./files/yysh.json', JSON.stringify(data));
    console.log("写入 yysh.json 成功");

    re = {
      code: 1,
      msg: "写入成功"
    }
  } catch (error) {
    console.log("写入失败" + error);

    re = {
      code: -1,
      msg: "写入失败" + error
    }
  }

  ctx.body = re;
})

router.post('/upload', async (ctx, next) => {
  try {
    const file = ctx.request.files.avatar; // 获取上传文件
    // 创建可读流
    const reader = fs.createReadStream(file.filepath);
    const fileResource = './images/yysh/' + file.originalFilename;
    // 创建可写流
    const upStream = fs.createWriteStream(fileResource);
    // 可读流通过管道写入可写流
    reader.pipe(upStream);

    ctx.body = {
      code: 1,
      data: {
        host: "http://" + ctx.host + "/images",
        url: "/yysh/" + file.originalFilename
      }
    }
  } catch (error) {
    ctx.body = {
      code: -1,
      data: {}
    }
  }
})

module.exports = router;